package com.wongoing.aop;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.wongoing.bus.util.Constants;
/**
 * 功能说明：继承java过滤器，对http请求进行过滤
 * 修改说明：
 * @author 吴兆强
 * @date 2018年7月9日 下午10:30:07
 * @version V0.1
 */
@Component
public class MyCorsFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;
    String url = request.getHeader("Origin");
    //允许跨域请求
    response.setHeader("Access-Control-Allow-Origin", url);
    //允许凭证,解决session跨域丢失问题
    response.setHeader("Access-Control-Allow-Credentials", "true");
    //允许前端请求的具体方法
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Origin, x-requested-with,content-type, " + Constants.AUTHORIZATION+","+Constants.XTOKEN);
    chain.doFilter(req, res);
  }
  public void init(FilterConfig filterConfig) {}
  public void destroy() {}
}